<template>
	<el-dialog
		:title="editData ? '编辑订单' : '新增订单'"
		v-model="dialogVisible"
		:destroy-on-close="true"
		width="80%"
	>
		<el-form
			ref="formRef"
			:model="formData"
			:rules="rules"
			label-width="100px"
			class="pr-8"
		>
			<!-- 基础信息 -->
			<div class="form-section">
				<div class="section-title">基础信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="订单编号" prop="orderNo">
							<el-input v-model="formData.orderNo" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="客户名称" prop="customerName" required>
							<el-select
								v-model="formData.customerName"
								placeholder="请选择客户"
								clearable
								filterable
								class="w-full"
							>
								<el-option label="选项1" value="1" />
							</el-select>
							<el-button
								type="primary"
								link
								class="absolute right-0 top-1"
								@click="handleAddCustomer"
							>
								新增客户
							</el-button>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="客户编号" prop="customerNo">
							<el-input v-model="formData.customerNo" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="发运类型" prop="shipType" required>
							<el-select
								v-model="formData.shipType"
								placeholder="请选择发运类型"
								clearable
								class="w-full"
							>
								<el-option label="整车运输" value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="目的地" prop="destination" required>
							<el-select
								v-model="formData.destination"
								placeholder="请选择目的地"
								clearable
								class="w-full"
							>
								<el-option label="选项1" value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="下单时间" prop="orderTime" required>
							<el-select
								v-model="formData.orderTime"
								placeholder="请选择下单时间"
								clearable
								class="w-full"
							>
								<el-option label="选项1" value="1" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 发货信息 -->
			<div class="form-section">
				<div class="section-title bg-[#fff3e8]">发货信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="联系人" prop="senderName" required>
							<el-input v-model="formData.senderName">
								<template #append>
									<el-button @click="openAddressBook('sender')"
										>地址簿</el-button
									>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="联系电话" prop="senderPhone" required>
							<el-input v-model="formData.senderPhone" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="地址编码" prop="senderAddressCode">
							<el-input v-model="formData.senderAddressCode" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="详细地址" prop="senderAddress" required>
							<el-input v-model="formData.senderAddress" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="计划发货时间" prop="planSendTime" required>
							<el-date-picker
								v-model="formData.planSendTime"
								type="datetime"
								placeholder="选择日期时间"
								class="!w-full"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 收货信息 -->
			<div class="form-section">
				<div class="section-title bg-[#e8f7f3]">收货信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="联系人" prop="receiverName" required>
							<el-input v-model="formData.receiverName">
								<template #append>
									<el-button @click="openAddressBook('receiver')"
										>地址簿</el-button
									>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="联系电话" prop="receiverPhone" required>
							<el-input v-model="formData.receiverPhone" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="地址编码" prop="receiverAddressCode">
							<el-input v-model="formData.receiverAddressCode" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="详细地址" prop="receiverAddress" required>
							<el-input v-model="formData.receiverAddress" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="计划收货时间" prop="planReceiveTime" required>
							<el-date-picker
								v-model="formData.planReceiveTime"
								type="datetime"
								placeholder="选择日期时间"
								class="!w-full"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 货物信息 -->
			<div class="form-section">
				<div class="section-title">
					<div class="title-text">货物信息</div>
					<el-button @click="handleAddNewProduct">
						<el-icon class="mr-1"><CirclePlus /></el-icon>新增货品
					</el-button>
				</div>
				<div class="mb-2">
					<el-button type="primary" @click="handleAddGoods">
						<el-icon class="mr-1"><Plus /></el-icon>添加
					</el-button>
				</div>
				<el-table :data="formData.goodsList" border>
					<el-table-column
						type="index"
						label="序号"
						width="60"
						align="center"
					/>
					<el-table-column label="货物名称" min-width="150">
						<template #default="{ $index }">
							<el-select
								v-model="formData.goodsList[$index].name"
								placeholder="请选择货物"
								clearable
								class="!w-full"
							>
								<el-option label="选项1" value="1" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="数量" width="150">
						<template #default="{ $index }">
							<el-input-number
								v-model="formData.goodsList[$index].quantity"
								:min="0"
								class="!w-full"
							/>
						</template>
					</el-table-column>
					<el-table-column label="单位" width="150">
						<template #default="{ $index }">
							<el-select
								v-model="formData.goodsList[$index].unit"
								placeholder="请选择单位"
								clearable
								class="!w-full"
							>
								<el-option label="吨" value="ton" />
								<el-option label="件" value="piece" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="需求车次" width="150">
						<template #default="{ $index }">
							<el-input-number
								v-model="formData.goodsList[$index].requiredTimes"
								:min="0"
								class="!w-full"
							/>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="80" align="center">
						<template #default="{ $index }">
							<el-button type="danger" link @click="handleDeleteGoods($index)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 费用信息 -->
			<div class="form-section">
				<div class="section-title">费用信息</div>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="运费总计" prop="totalFreight" required>
							<el-input-number
								v-model="formData.totalFreight"
								:min="0"
								:precision="2"
								class="!w-full"
							>
								<template #append>元</template>
							</el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="基础运费" prop="baseFreight">
							<el-input-number
								v-model="formData.baseFreight"
								:min="0"
								:precision="2"
								class="!w-full"
							>
								<template #append>元</template>
							</el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="加急费用" prop="urgentFee">
							<el-input-number
								v-model="formData.urgentFee"
								:min="0"
								:precision="2"
								class="!w-full"
							>
								<template #append>元</template>
							</el-input-number>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<!-- 订单备注 -->
			<div class="form-section">
				<div class="section-title">订单备注</div>
				<el-form-item prop="remark">
					<el-input
						v-model="formData.remark"
						type="textarea"
						:rows="3"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
			</div>
		</el-form>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleSubmit" :loading="submitting">
				保存
			</el-button>
		</template>
	</el-dialog>

	<!-- 新增客户弹框 -->
	<AddCustomer ref="addCustomerRef" />

	<!-- 地址簿选择弹框 -->
	<AddressSelect ref="addressSelectRef" @select="handleSelectAddress" />

	<!-- 新增货品弹框 -->
	<AddCargo ref="addCargoRef" @success="handleAddProductSuccess" />
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, CirclePlus } from '@element-plus/icons-vue';
import AddCustomer from '/@/views/tscompany/CustomerMgmt/components/addCustomer.vue';
import AddressSelect from '/@/views/tscompany/CustomerMgmt/components/AddressSelect.vue';
import AddCargo from '/@/views/tscompany/CargoMgmt/components/addCargo.vue';

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	editData: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['update:modelValue', 'success']);

const dialogVisible = ref(false);
const formRef = ref(null);
const submitting = ref(false);
const addCustomerRef = ref(null);
const addressSelectRef = ref(null);
const addCargoRef = ref();

// 表单数据
const formData = reactive({
	orderNo: 'DD20250420001',
	customerName: '',
	customerNo: '',
	shipType: '',
	destination: '',
	orderTime: '',
	senderName: '',
	senderPhone: '',
	senderAddressCode: '',
	senderAddress: '',
	planSendTime: '',
	receiverName: '',
	receiverPhone: '',
	receiverAddressCode: '',
	receiverAddress: '',
	planReceiveTime: '',
	goodsList: [],
	totalFreight: 0,
	baseFreight: 0,
	urgentFee: 0,
	remark: '',
});

// 表单校验规则
const rules = {
	customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
	shipType: [{ required: true, message: '请选择发运类型', trigger: 'change' }],
	destination: [{ required: true, message: '请选择目的地', trigger: 'change' }],
	orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
	senderName: [
		{ required: true, message: '请输入发货联系人', trigger: 'blur' },
	],
	senderPhone: [
		{ required: true, message: '请输入发货联系电话', trigger: 'blur' },
	],
	senderAddress: [
		{ required: true, message: '请输入发货详细地址', trigger: 'blur' },
	],
	planSendTime: [
		{ required: true, message: '请选择计划发货时间', trigger: 'change' },
	],
	receiverName: [
		{ required: true, message: '请输入收货联系人', trigger: 'blur' },
	],
	receiverPhone: [
		{ required: true, message: '请输入收货联系电话', trigger: 'blur' },
	],
	receiverAddress: [
		{ required: true, message: '请输入收货详细地址', trigger: 'blur' },
	],
	planReceiveTime: [
		{ required: true, message: '请选择计划收货时间', trigger: 'change' },
	],
	totalFreight: [
		{ required: true, message: '请输入运费总计', trigger: 'blur' },
	],
};

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	(val) => {
		dialogVisible.value = val;
		if (val && props.editData) {
			// 编辑模式，填充表单数据
			Object.assign(formData, props.editData);
		}
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
	if (!val) {
		formRef.value?.resetFields();
		Object.assign(formData, {
			orderNo: 'DD20250420001',
			customerName: '',
			customerNo: '',
			shipType: '',
			destination: '',
			orderTime: '',
			senderName: '',
			senderPhone: '',
			senderAddressCode: '',
			senderAddress: '',
			planSendTime: '',
			receiverName: '',
			receiverPhone: '',
			receiverAddressCode: '',
			receiverAddress: '',
			planReceiveTime: '',
			goodsList: [],
			totalFreight: 0,
			baseFreight: 0,
			urgentFee: 0,
			remark: '',
		});
	}
});

// 添加货物
const handleAddGoods = () => {
	formData.goodsList.push({
		name: '',
		quantity: 0,
		unit: '',
		requiredTimes: 1,
	});
};

// 删除货物
const handleDeleteGoods = (index) => {
	formData.goodsList.splice(index, 1);
};

// 取消
const handleCancel = () => {
	dialogVisible.value = false;
};

// 提交
const handleSubmit = async () => {
	if (!formRef.value) return;
	await formRef.value.validate((valid, fields) => {
		if (valid) {
			submitting.value = true;
			// TODO: 调用保存接口
			console.log('提交的数据：', formData);
			setTimeout(() => {
				submitting.value = false;
				ElMessage.success('保存成功');
				dialogVisible.value = false;
				emit('success', formData);
			}, 1000);
		} else {
			console.log('校验失败', fields);
		}
	});
};

// 新增客户
const handleAddCustomer = () => {
	addCustomerRef.value?.open({
		code: 'KH' + new Date().getTime(), // 生成临时客户编号
	});
};

const currentAddressType = ref(''); // 当前操作的地址类型：sender/receiver

// 打开地址簿
const openAddressBook = (type) => {
	currentAddressType.value = type;
	addressSelectRef.value?.open();
};

// 选择地址回调
const handleSelectAddress = (address) => {
	// TODO: 根据当前操作类型（发货/收货）填充对应的表单数据
	const { contact, phone, detail } = address;
	if (currentAddressType.value === 'sender') {
		formData.senderName = contact;
		formData.senderPhone = phone;
		formData.senderAddress = detail;
	} else {
		formData.receiverName = contact;
		formData.receiverPhone = phone;
		formData.receiverAddress = detail;
	}
};

// 打开新增货品弹框
const handleAddNewProduct = () => {
	addCargoRef.value?.open();
};

// 新增货品成功
const handleAddProductSuccess = () => {
	// TODO: 刷新货品列表
	// 不需要手动关闭弹框，组件内部会处理
};
</script>

<style lang="scss" scoped>
.form-section {
	margin-bottom: 32px;

	.section-title {
		font-size: 15px;
		font-weight: 500;
		margin-bottom: 24px;
		padding: 10px 16px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
		position: relative;
		display: flex;
		align-items: center;
		gap: 10px;
		/* justify-content: space-between; */

		&::before {
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 4px;
			height: 16px;
			background-color: var(--el-color-primary);
			border-radius: 0 2px 2px 0;
		}
	}

	.el-row {
		row-gap: 0;
	}
}

:deep(.el-dialog__body) {
	padding: 20px 24px;
}

:deep(.el-form) {
	.el-form-item {
		margin-bottom: 18px !important;

		/* &:last-child {
			margin-bottom: 0;
		} */

		.el-form-item__label {
			padding-bottom: 4px;
			line-height: 20px;
			font-size: 14px;
			color: var(--el-text-color-regular);
		}

		.el-form-item__content {
			line-height: 32px;

			.el-input__wrapper,
			.el-select .el-input__wrapper,
			.el-date-editor.el-input__wrapper {
				box-shadow: 0 0 0 1px #dcdfe6 inset;
				padding: 1px 11px;
				height: 32px;
				line-height: 32px;

				&:hover {
					box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
				}

				&.is-focus {
					box-shadow: 0 0 0 1px var(--el-color-primary) inset;
				}
			}

			.el-textarea__inner {
				padding: 8px 11px;
				min-height: 80px;
				box-shadow: 0 0 0 1px #dcdfe6 inset;

				&:hover {
					box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
				}

				&:focus {
					box-shadow: 0 0 0 1px var(--el-color-primary) inset;
				}
			}
		}

		&.is-required {
			.el-form-item__label::before {
				margin-right: 2px;
			}
		}
	}
}

:deep(.el-table) {
	border: 1px solid var(--el-border-color-lighter);
	border-radius: 4px;

	.el-table__header {
		th.el-table__cell {
			background-color: var(--el-fill-color-light);
			color: var(--el-text-color-regular);
			font-weight: 500;
		}
	}

	.el-table__body {
		td.el-table__cell {
			padding: 8px;
		}
	}

	.el-input-number.is-without-controls {
		.el-input__wrapper {
			padding-right: 11px;
		}
	}
}

// 发货和收货信息区块样式
.form-section {
	.section-title {
		&.bg-\[\#fff3e8\] {
			background-color: var(--el-color-warning-light-9);
			color: var(--el-color-warning-dark-2);
			&::before {
				background-color: var(--el-color-warning);
			}
		}

		&.bg-\[\#e8f7f3\] {
			background-color: var(--el-color-success-light-9);
			color: var(--el-color-success-dark-2);
			&::before {
				background-color: var(--el-color-success);
			}
		}
	}
}

// 按钮样式优化
:deep(.el-button) {
	&.el-button--primary {
		--el-button-hover-bg-color: var(--el-color-primary-light-3);
		--el-button-hover-border-color: var(--el-color-primary-light-3);
	}

	&.el-button--default {
		&:not(:disabled):hover {
			color: var(--el-color-primary);
			border-color: var(--el-color-primary-light-3);
			background-color: var(--el-color-primary-light-9);
		}
	}
}

// 地址簿按钮样式
:deep(.el-input-group__append) {
	.el-button {
		border: none;
		padding: 5px 12px;
		background-color: var(--el-fill-color-light);

		&:hover {
			color: var(--el-color-primary);
			background-color: var(--el-color-primary-light-9);
		}
	}
}

// 添加货物按钮样式
.mb-2 {
	.el-button {
		padding: 8px 16px;
		font-size: 14px;

		.el-icon {
			font-size: 16px;
		}
	}
}

// 弹窗底部按钮
:deep(.el-dialog__footer) {
	padding: 16px 24px;
	border-top: 1px solid var(--el-border-color-lighter);

	.el-button + .el-button {
		margin-left: 12px;
	}
}

.order-dialog {
	:deep(.el-dialog__body) {
		padding: 20px 24px;
	}

	.section-title {
		font-size: 16px;
		font-weight: 500;
		color: var(--el-text-color-primary);
		margin-bottom: 16px;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.title-text {
			display: flex;
			align-items: center;
		}
	}
}
</style>
